<template>
  <div class="scheduling-page">
    <GhNavBar title="预约排期设置"  rightText="添加时段" @click-right="clickRight" />
    <div class="top-box">
        <div class="top_lf"><span>*</span>预约时段排期设置</div>
        <div class="top_rg">七天可约  <gh-icon class="icon" name="consult-rg"></gh-icon></div>
    </div>
    <div class="calendar-box">
       <!-- 预约日期列表 -->
        <van-swipe
        :loop="false"
        :show-indicators="false"
        :width="60"
         ref="dateSwipe"
      >
        <van-swipe-item v-for="date in tran_dates" :key="date" >
          <div class="date" @click="selectDate(date)" :class="{ active: selectedDate === date.date }">
                <p class="month">{{date.month}}月</p>
                <p class="day">{{date.day}}</p>
                <p class="week">{{date.week}}</p>
                <div class="status">
                    <p>点击</p>
                    <p>查看</p>
                </div>
          </div>
        </van-swipe-item>
      </van-swipe>
      <div class="date-info">
        <!-- 空闲时间展示表 -->
        <div class="availability-box" v-if="timeSlots.length>0">
             <div  class="time-slot"  v-for="timeSlot in timeSlots" :key="timeSlot.id" @click="selectTime_Slot(timeSlot)"
             :class="{ 'selected': timeSlot.id === selectedTimeSlotId, 'booked': timeSlot.is_booked }"> 
              {{ timeSlot.start_time }} - {{ timeSlot.end_time }}
              <div class="is_selected" v-if="timeSlot.id===selectedTimeSlotId"><gh-icon class="icon" name="consult-selected"></gh-icon></div>
              <div class="is_booked" v-else-if="timeSlot.is_booked===null||0">可预约</div>
              <div class="unbooked" v-else-if="timeSlot.is_booked===1">已预约</div>
            </div>
        </div>
        <div class="nothing-info" v-else>
            <van-empty  image-size="100" description="暂无空闲信息，去添加？" />
        </div>
      </div>
    </div>
    <!-- 弹出添加时段的弹窗 -->
    <div class="addSche">
        <van-popup class="popup"   v-model:show="show" @close="close" round closeable position="top">
            <h2>添加时间段</h2>
          <van-field 
           v-model="dateTime"
           readonly
           label="日期"
           placeholder="点击选择日期时间"
           @click="showPicker=true"
           clickable required  autocomplete="off"></van-field>
              <!-- 展示日期选择器   -->
              <van-popup v-model:show="showPicker" round position="bottom">
                <van-datetime-picker
                    v-model="selectedDay"
                    type="date"
                    title="请选择日期"
                    :min-date="minDate"
                    :max-date="maxDate"
                    @cancel="showPicker=false"
                    @confirm="onConfirm"
                    :format="dateFormat"
              />
            </van-popup> 
            <van-field  v-model="timeSlot"  readonly  placeholder="选择时间段"  label="时间段"
             clickable required  autocomplete="off"  @click="showTimeSlotsPickerFn"  is-link>
            </van-field> 
            <van-popup v-model:show="showTimeSlotsPicker" round position="bottom">
                <van-picker
                  title="请选择时间段"
                  :columns="time_periods"
                  @cancel="showTimeSlotsPicker = false"
                  @confirm="onTimeSlotConfirm"
                />
              </van-popup>
          <van-button native-type="submit" @click="addTime" :loading="isRegistering" :disabled="isRegistering" block round type="primary">
            确定
          </van-button>
          </van-popup>
    </div>
  </div>
</template>

<script setup>
import {ref,reactive,onBeforeMount,computed,onMounted,watch,onBeforeUnmount} from "vue"
import { Toast, Dialog } from 'vant'
import 'vant/es/toast/style'
import{useRouter,useRoute}from 'vue-router'
import {useUserStore}from '@/stores'
import{getconsultantInfoByaccount,updateConsultantInfo, gettimeperiods,getavailableTimeBydate,addAvailableTimeBycoun_id}from '@/services/consultant'
import {getDetailConsultantInfo,getavailableTime,getAvailableToday,getAvailableByTime,appointment} from '@/services/booking'
const route =useRoute()
const router =useRouter();  
const store = useUserStore()
//选择添加预约时间段响应式变量
const timeSlot=ref('')
const showTimeSlotsPicker=ref(false)
//点击添加时间段查询可预约时间段
const showTimeSlotsPickerFn=async()=>{
    if(dateTime.value==''){
        Toast('请先选择日期')
        return
    }
    const id =personalInfo.value.id
    const time_preiodsData=await  gettimeperiods()
    time_periods.value=time_preiodsData.data
    const res=await getavailableTimeBydate(id,dateTime.value)
    const filteredTimeSlot=time_periods.value.filter(item=>
        !res.data.includes(item)
    )
    time_periods.value=filteredTimeSlot
    showTimeSlotsPicker.value=true
    
   }
//定义时间选择器信息
    const minDate = new Date();
    const maxDate = new Date(new Date().getTime() + 6 * 24 * 60 * 60 * 1000); // 7天后的日期
    const dateFormat = 'yyyy-MM-dd';
//选择日期
  const onConfirm = (value) => {
        const date = new Date(value);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');  
        const formattedDate = `${year}-${month}-${day}`;
        dateTime.value=formattedDate
       showPicker.value=false
    };
//选择预约的时间段
const onTimeSlotConfirm=(value)=>{
      timeSlot.value=value
      showTimeSlotsPicker.value=false
}
//时间选择器选择日期
   const selectedDay=ref(null)
//定义添加时段的表单提交数据
const dateTime=ref('')


//存储空闲时间段数据
const timeSlots=ref([])
const show=ref(false)
const showPicker=ref(false)
// 选中的日期
 const selectedDate = ref(null);
 const dates = ref([]);
 const tran_dates=ref([])
 // 初始化日期列表
 const initDates = () => {
      const currentDate = new Date();
      for (let i = 0; i < 7; i++) {
        const date = new Date(currentDate);
        date.setDate(date.getDate() + i);
        dates.value.push(date);
      }
      const formttedDates= dates.value.map(date=>{
        return {date:formData(date),month:String(date.getMonth() + 1).padStart(2, '0'),day:String(date.getDate()).padStart(2, '0'),week:date.toLocaleString('default',{weekday:'short'})}
      })
      tran_dates.value=formttedDates
      selectedDate.value = formData(dates.value[0]);
 };
    
// 格式化日期
const formData = (date) => {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
//定义选中的响应式变量
const selectedTimeSlotId=ref()
const booking_time=ref()

//选择预约时间段
const selectTime_Slot=(timeSlot)=>{
   selectedTimeSlotId.value=timeSlot.id
   booking_time.value=timeSlot
}

 // 选择日期
 const selectDate = async(date) => {
      selectedDate.value = date.date
      const id =personalInfo.value.id
      const time=selectedDate.value
      const res=await getAvailableByTime(id,time)
      const timeData=res.data
      //对时间进行格式处理
      const timeDatas= timeData.map(row=>{
     const date=row.start_time.split(' ')[0];
     const timePart_start=row.start_time.split(' ')[1]
     const timePart_end=row.end_time.split(' ')[1]
     // 再次拆分时间部分并获取小时和分钟部分
    var timeParts_start = timePart_start.split(":");
    var timeParts_end = timePart_end.split(":");
    var timePartData_start = timeParts_start[0] + ":" + timeParts_start[1]; // 只获取小时和分钟    
    var timePartData_end = timeParts_end[0] + ":" + timeParts_end[1];
    return{
      id:row.id,
      coun_id:row.coun_id,
      date:date,
      start_time:timePartData_start,
      end_time:timePartData_end,
      is_booked:row.is_booked
    }
   })
     timeSlots.value=timeDatas
};

initDates()
const personalInfo=ref('')
//预约时间段响应式数据
const time_periods=ref({})
onMounted(async()=>{
    const account=JSON.parse(localStorage.getItem('gh-user')).user.userData.account
    const res=await getconsultantInfoByaccount(account)
    personalInfo.value=res.data
    const id =personalInfo.value.id
    const today =formData(new Date())
    //组件挂载时渲染今日空闲时间
   const todayTime=await getAvailableToday(id,today)
    const todayTimeData=todayTime.data
   const todayTimeSlot= todayTimeData.map(row=>{
     const date=row.start_time.split(' ')[0];
     const timePart_start=row.start_time.split(' ')[1]
     const timePart_end=row.end_time.split(' ')[1]
     // 再次拆分时间部分并获取小时和分钟部分
    var timeParts_start = timePart_start.split(":");
    var timeParts_end = timePart_end.split(":");
    var timePartData_start = timeParts_start[0] + ":" + timeParts_start[1]; // 只获取小时和分钟    
    var timePartData_end = timeParts_end[0] + ":" + timeParts_end[1];
    return{
      id:row.id,
      coun_id:row.coun_id,
      date:date,
      start_time:timePartData_start,
      end_time:timePartData_end,
      is_booked:row.is_booked
     }
   })
    timeSlots.value=todayTimeSlot
})
const isRegistering = ref(false);
//右上角添加时段
const clickRight=()=>{
    show.value=true
}
//确定添加空闲时间
const addTime=async()=>{
    if(dateTime.value==''){
       Toast('请先选择日期')
       return
    }
    if(timeSlot.value==''){
      Toast('请先选择时间段')
      return
    }
    const id =personalInfo.value.id
    const formData=new FormData();
    formData.append('coun_id',id)
    formData.append('date',dateTime.value)
    formData.append('timeSlot',timeSlot.value)
    const res=await addAvailableTimeBycoun_id(formData).then((response)=>{
      return response
    }).catch((error)=>{
     return error
    })
    if(res.status!==201){
   if(res.response.status==402){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
       }
    }  
    console.log(res)
    Toast.success('添加成功!')
    show.value=false
    // 刷新当前页面
     location.reload();
}

//取消添加时段
const close=()=>{
     dateTime.value=''
     timeSlot.value=''
}



</script>

<style lang="scss" scoped>
.scheduling-page{
    width: 100%;
    height: 90vh;
    background-color: #f5f5f5;
    .top-box{
        margin-top: 48px;
        width: 100%;
        height: 50px;
        padding: 0 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #FEF2CE;
        .top_lf{
            font-size: 17px;
            font-weight: bold;
            span{
                color: red;
                margin-right: 5px;
            }
        }
        .top_rg{
            font-size: 15px;
            font-weight: bold;
            color: var(--gh-price);
            .icon{
                position: relative;
                top: 3px;
            }
        }
    }
    .calendar-box{
                .van-swipe{
                    margin-top: 15px;
                    height: 130px;
                    width: 100%;
                    .date{
                        text-align: center;
                        width: 100%;
                        height: 100%;
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                        .month{
                            font-size: 12px;
                            color: #808185;
                        }
                        .day{
                            font-size: 17px;
                            font-weight: bold;
                        }
                        .week{
                            font-size: 10px;
                        }
                        .status{
                            display: flex;
                            flex-direction: column;
                            font-size: 10px;
                            background-color:#e9eaf1;
                            margin-top: 10px;
                            height: 45px;
                            width: 40px;
                            border-radius:6px;
                            align-items: center;
                            justify-content: center;
                            text-align: center;
                        }
                    }
                    .date.active{
                        background-color: var(--gh-primary);
                        color: #fff;
                        border-radius: 8px;
                        .status{
                            color: #000;
                            background-color: #fff;
                        }
                    }
                }
                .date-info{
                    width: 100%;
                    text-align: center;
                    /* height: 200px; */
                    .info{
                         width: 100%;
                    }
                    .nothing-info{
                        margin-top: 10px;
                        width: 100%;
                        height:200px;
                        background-color: #f5f5f5;
                        .van-empty{
                            height: 100%;
                            width: 100%;
                        }
                    }
                    .availability-box{
                         margin-top: 15px;
                         width: 100%;
                         display: flex;
                         flex-wrap: wrap;
                         justify-content: flex-start;
                         align-items: center;
                         .time-slot{
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          margin: 8px 5px;
                          width: 30%;
                          height: 45px;
                          border: 1px solid #ccc;
                          padding: 5px;
                          border-radius: 8px;
                          cursor: pointer;
                          text-align: center;
                          vertical-align: middle;
                          font-size: 12px;
                          font-weight: bold;
                          position: relative;
                          .is_booked{
                            position: absolute;
                            top: 0;
                            right: 3px;
                            font-size: 10px;
                            color: var(--gh-price);
                            font-family: '黑体';
                         }
                         .unbooked{
                          position: absolute;
                            top: 0;
                            right: 3px;
                            font-size: 10px;
                            color: var(--gh-price);
                            font-family: '黑体';
                         }
                         .is_selected{
                            position: absolute;
                            top: -5px;
                            right: 0px;
                            font-size: 20px;
                            color: var(--gh-price);
                            font-family: '黑体';
                         }
                         &.selected{
                          background-color: lightblue;
                         }
                         &.booked{
                          color: gray;
                          opacity: 0.5;
                          pointer-events: none;
                          cursor: not-allowed;
                         }
                        }
                     
                    }
                }

     }
    .addSche{
        display: flex;
        text-align: center;
       justify-content: center;
       flex-direction: column;
       .van-popup{
           .van-field{
              font-family: '黑体';
              font-size: 16px;
              .memu{
                width: 300px;
                position: relative;
                .custom-dropdown-item{
                    /* position: absolute; */
                    /* top: 0; */
                    /* left: 0; */
                }
              }
                

          }
         h2{
            margin-bottom: 5px;
            margin-top: 10px;
            font-size: 18px;
            font-weight: 600;
            font-family: '宋体';
          }
        .van-button{
              width: 80%;
              left: 50%;
              margin-top: 10px;
              transform: translate(-50%);
              height: 40px;
              margin-bottom: 20px;
              font-size: 16px;
             }
         }
      }


}
</style>
